package com.seestech.sell.web.monitor;

import com.github.pagehelper.Page;
import com.seestech.sell.common.annotation.RecordLog;
import com.seestech.sell.common.config.ApplicationConfig;
import com.seestech.sell.common.utils.Constants;
import com.seestech.sell.common.utils.FileUtils;
import com.seestech.sell.common.utils.ResponseUtils;
import com.seestech.sell.domain.model.Agent;
import com.seestech.sell.domain.model.AgentTaskInfo;
import com.seestech.sell.domain.model.Screenshots;
import com.seestech.sell.domain.model.User;
import com.seestech.sell.domain.model.enums.CodeEnums;
import com.seestech.sell.service.IAgentService;
import com.seestech.sell.service.IAgentTaskService;
import com.seestech.sell.service.IScreenShotsService;
import com.seestech.sell.web.SuperController;
import org.apache.ibatis.session.RowBounds;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by idiot on 2017/1/17.
 * @description  屏幕画面监控
 */
@Controller
@RequestMapping(value = "monitor/screen")
public class ScreenController extends SuperController {
    private static Logger logger = LoggerFactory.getLogger(ScreenController.class);

    @Resource
    private IAgentService agentService;
    @Resource
    private IScreenShotsService screenShotsService;
    @Resource
    private ApplicationConfig applicationConfig;
    @Resource
    private IAgentTaskService agentTaskService;

    //加载page页面
    @RecordLog(value = "加载终端监控页面")
    @RequiresPermissions(value = "monitor:screen:page")
    @RequestMapping(value = "page", method = RequestMethod.GET)
    public String toPage(){
        return "monitor/screen/page";
    }

    /**
     * @description  加载画面监控数据
     * @param pageNo
     * @param pageSize
     * @param model
     * @return
     */
    @RequestMapping(value = "data", method = RequestMethod.POST)
    public String data(Integer pageNo, @RequestParam(defaultValue="10")Integer pageSize, Model model, Agent info){
        //分页加载用户所有终端  联合 终端截图信息表
        info.setUserId(getUser().getUserId());
        Page<Agent> agents = agentService.getAllAgentsScreenshots(new RowBounds((pageNo-1)*pageSize, pageSize), info);
        for (Agent agent : agents){
            if(agent.getImageName() != null)
                agent.setImageUrl(FileUtils.addPathSeparate(applicationConfig.getUploadUrl(), applicationConfig.getBaseDirectory(), Constants.Regular.monitor_wall, agent.getAgentCode(), agent.getImageName()));
        }
        model.addAttribute("lists", agents);
        return "monitor/screen/data";
    }

    /**
     * @description  前往截图墙页面
     * @param model
     * @param agentCode
     * @return
     */
    @RequestMapping(value = "{agentCode}/toscreenShots", method = RequestMethod.GET)
    public String toScreenShotsPage(Model model, @PathVariable("agentCode") String agentCode){
        model.addAttribute("agentCode", agentCode);
        return "monitor/screen/screenShots";
    }

    /**
     * @description  回传画面截图
     * @param model
     * @param agentCode
     * @return
     */
    @RequestMapping(value = "{agentCode}/imagedata", method = RequestMethod.POST)
    public String images(Model model, @PathVariable("agentCode") String agentCode,
                         Integer pageNo, @RequestParam(defaultValue="10")Integer pageSize){
        logger.info("读取监控图片信息======>开始");
        //根据agentCode获取图片信息
        logger.info("监控图片文件路径=======>"+ Constants.Regular.monitor_wall);
        //获取终端截图文件
        Page<Screenshots> screenshotsList = screenShotsService.getScreenshotsByAgentCode(new RowBounds((pageNo-1)*pageSize, pageSize), agentCode);
        //遍历集合
        for (Screenshots screenshots : screenshotsList){
            screenshots.setUrl(FileUtils.addPathSeparate(applicationConfig.getUploadUrl(), applicationConfig.getBaseDirectory(), Constants.Regular.monitor_wall, agentCode, screenshots.getImageName()));
        }
        model.addAttribute("lists", screenshotsList);
        logger.info("读取监控图片信息=======>结束");
        return "monitor/screen/imagedata";
    }


    //手动发送截屏消息
    @RequestMapping(value = "screenshots", method = RequestMethod.POST)
    public void screenshots(Integer pageNo, @RequestParam(defaultValue="10")Integer pageSize){
        logger.info("手动发送截屏消息=======>开始");
        User user = getUser();
        if(user == null) {
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "用户信息失效，请重新登录");
            return;
        }
        //获取终端信息
        Agent item = new Agent();
        item.setUserId(user.getUserId());
        List<Agent> agents = agentService.getAllAgentsByUserId(new RowBounds(0, Integer.MAX_VALUE), item);
        // String[] agentCodes = new String[pageSize];
        //遍历所有在线的终端  构造消息字符串
        for(int i=0; i<agents.size(); i++){
            Agent agent = agents.get(i);
            //判断是否在线
            if(agent.getOnlineStatus() == 0) {
                AgentTaskInfo info = new AgentTaskInfo();
                info.setAgentCode(agent.getAgentCode());
                info.setCode(CodeEnums.four.getValue());
                info.setCreateUser(getUser().getUserId());
                agentTaskService.insert(info);
            }
        }
        // AgentTask.getInstance().nine(agentCodes);
        logger.info("手动发送截屏消息=======>结束");
        ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "消息发送成功");
    }

    //批量删除
    @RequestMapping(value = "deleteBatch", method = RequestMethod.POST)
    public void deleteBatch(@RequestParam("ids[]") Long[] screenshotsIds){
        screenShotsService.deleteBatch(screenshotsIds);
        ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "批量删除信息成功");
    }
}
